/**
 * Created by sxx on 2017/10/11.
 */
import "./index.less";
import { projSts } from "../config.js";

import bidListTpl from "./apply_chrm_list.handlebars";
import paginationTpl from "./paging.handlebars";

let token = sessionStorage.getItem('token');
let splrStsList = {
    "01":"注册",
    "02":"准入申请",
    "03":"预备供方",
    "04":"开发申请",
    "05":"合格供方",
    "06":"淘汰",
    "07":"黑名单",
    "08":"准入申请失败",
    "09":"开发申请失败",
    "10":"主数据申请失败",
    "11":"BPM申请成功",
    "12":"主数据申请"
};
var ApplyList = {
    pageNo: 1,
    pageSize: 20,
    maxPage: 1,
    isFirstPage: false,
    isLastPage: false,
    total: 0,
    data:{},
    init: function() {
        this.getData()
            .then(this.renderList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    },
    getData: function() {
        return new Promise((resolve, reject) => {
            let self = this;
            let data = self.data;
            $.ajax({
                url: HOST_ADDR + `/cpmp/splrMng/splrList/`+this.pageNo+'/'+this.pageSize,
                type: 'post',
                dataType: 'json',
                headers: {
                    'access_token': token,
                    'login_type': 'ums',
                    "splrStatus": '02,03,04,05,06,07,08,09,10,11,12'
                },
                data:JSON.stringify(data),
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        console.log(resp);
                        resolve(resp);
                    } else {
                        alert(resp.msgInf);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });
    },
    // 渲染列表

    renderList: function(resp) {

        let self = ApplyList;
        // 处理数据begin
        let resultHtml = '';
        if(resp.data==''||resp.data==null){
            self.total = 0;
            self.isFirstPage = self.pageNo === 1;
            self.maxPage = 1;
            self.isLastPage = true;
        }else{
            self.total = resp.data.count;
            self.isFirstPage = self.pageNo === 1;
            self.maxPage = Math.ceil(self.total / self.pageSize);
            console.log(resp.data);
            $.each(resp.data.list,function(index,item){
                item.splrStsFmt = splrStsList[item.splrSts];
                item.ishow = item.chrmShow==="1";
            });
            // 处理数据end
            if (self.pageNo * self.pageSize >= self.total) {
                self.isLastPage = true;
            } else {
                self.isLastPage = false;
            }
            resultHtml = bidListTpl({ applyList: resp.data.list });
        }
        $('.J_apply-list').html(resultHtml);
    },

    // 渲染分页
    renderPagination: function() {
        let self = ApplyList;
        let pageList = [];
        for (let i = 0; i < self.maxPage; i++) {
            pageList.push({ idx: i + 1 });
        }
        let paginationHtml = paginationTpl({
            begin: (self.pageNo - 1) * self.pageSize + 1,
            end: self.isLastPage ? self.total : self.pageNo * self.pageSize,
            total: self.total,
            isLastPage: self.isLastPage,
            isFirstPage: self.isFirstPage,
            pageList: pageList

        });
        $('.J_pagination').html(paginationHtml);
        $('.page-item').each((index, item) => {
            if ($(item).data('index') === self.pageNo) {
                $(item).addClass('active');
            }
            var basepage = self.pageNo;
            if(basepage<=5){
                basepage = 5;
            }
            if((-5 <= (parseInt($(item).data('index'))-basepage)) && ((parseInt($(item).data('index'))-basepage)<=5)){
                $(item).removeClass('hidden');
                $(item).find("span").removeClass("hidden");
            }else{
                $(item).addClass('hidden');
                $(item).find("span").addClass("hidden");
            }
        });
    },

    // 绑定事件
    bindEvent: function() {
        let self = ApplyList;
        $('.J_prev').unbind().click(function() {
            if (self.pageNo > 1) {
                self.pageNo = self.pageNo - 1;
                self.getData()
                    .then(self.renderList)
                    .then(self.renderPagination)
                    .then(self.bindEvent);
            }
        });
        $('.J_next').unbind().click(function() {
            console.log('J_next');
            if (self.pageNo < self.maxPage) {
                console.log('aaa');
                self.pageNo = self.pageNo + 1;
                self.getData()
                    .then(self.renderList)
                    .then(self.renderPagination)
                    .then(self.bindEvent);
            }

        });
        $('.page-item').off().on('click', function() {
            let $item = $(this);
            console.log('aaaa');
            if (!$item.hasClass('active')) {
                self.pageNo = $item.data('index');
                self.getData()
                    .then(self.renderList)
                    .then(self.renderPagination)
                    .then(self.bindEvent);
            }
        });

        //搜索
        $('.searchSplr').unbind().click(function(){
            var searNam = jQuery('.searNam').val();
            // var searStatus = jQuery('.searStatus').val();
            if (searNam != '' && searNam != null) {
                self.data.fullNam = searNam;
            }
            console.log(self.data);
            self.getData()
                .then(self.renderList)
                .then(self.renderPagination)
                .then(self.bindEvent);
        });

        // 设置供应商风采是否展示到门户网站上

        $('.addPublish .btn').click(function(){
			let splrId = $(this).attr("splrId");
            let chrmShow = $(this).attr("chrmShow");
            let targetVal = (chrmShow=='1') ? "02" :"01";
            let data={'splrId':splrId,'chrmShowSts':targetVal};
        	console.log(splrId,chrmShow,targetVal);
        	console.log(data);
            $.ajax({
                type: 'POST',
                url:HOST_ADDR + `/cpmp/splrChrm/setSplrChrm`,
                dataType: 'json',
                headers: {
                   'access_token': token,'login_type':'ums'
                },
                data:JSON.stringify(data),
                contentType: "application/json",
                success: function (resp) {
                    if (resp.success) {
                        console.log(resp);
                        if(chrmShow==1){ // 取消展示
                            $('.addPublish .btn[splrId='+splrId+']').removeClass("green").addClass("grey").attr("chrmShow","0").html("未展示");
                        }else{ // 设置为展示
                            $('.addPublish .btn[splrId='+splrId+']').removeClass("grey").addClass("green").attr("chrmShow","1").html("已展示");
                        }
                        alert("操作成功！");
                    }
                    else {
                        alert(resp.msgInf);
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        });
        
        // $("#submitPub").click(function(){
        // 	var splrIds = [];
        // 	$("#publishGroup tr").each(function(){
        // 		var tmpid = $(this).find("td[splrId]").attr("splrId");
        // 		splrIds.push(Number(tmpid));
        // 	});
        // 	splrIds.shift();
        // 	console.log(splrIds);
        // 	var data = splrIds;
        // 	$.ajax({
        // 		type: 'POST',
        // 		url:HOST_ADDR + `/cpmp/splrChrm/setSplrChrm`,
	     //        dataType: 'json',
	     //        headers: {
	     //            'access_token': token,'login_type':'ums'
	     //        },
		 //        data:JSON.stringify(data),
	     //        contentType: "application/json",
	     //        success: function (resp) {
	     //            if (resp.success) {
	     //                console.log(resp);
	     //                alert("发布成功！");
	     //            }
	     //            else {
	     //                alert("请添加供应商到风采发布列表");
	     //            }
	     //        },
	     //        error: function (err) {
	     //            console.log(err);
	     //        }
        // 	});
        // });
        
    }
};

App.init();
ApplyList.init();

